package com.zhan.rkforum.controller;

import com.zhan.rkforum.bean.DiscussPost;
import com.zhan.rkforum.bean.Page;
import com.zhan.rkforum.bean.User;
import com.zhan.rkforum.service.DiscussPostService;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.service.MessageService;
import com.zhan.rkforum.service.UserService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @GetMapping(value = "/index")
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode){
        page.setPath("/index?orderMode=" + orderMode);
        int rows = discussPostService.selectDiscussPostRows(0);
        page.setRows(rows);
        List<DiscussPost> list = discussPostService.selectDiscussPosts(0, orderMode,page.getOffset(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        list.forEach(discussPost -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("post",discussPost);
            User user = userService.findUserById(Integer.parseInt(discussPost.getUserId()));
            map.put("user",user);
            Long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
            map.put("likeCount",likeCount);
            discussPosts.add(map);
        });
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("orderMode", orderMode);
        User user = hostHolder.getUser();
        if(user != null){
            int unReadNotice = messageService.unReadTopicNoticeCount(user.getId(), null);
            int unReadMessage = messageService.selectUnreadMessageCount(user.getId(), null);
            model.addAttribute("messageCount", unReadMessage + unReadNotice);
        }

        return "index";
    }


    @GetMapping("/error")
    public String toErrorPage(){
        return "/error/500";
    }

    @GetMapping("/denied")
    public String toDeniedPage(){
        return "/error/404";
    }

}
